package arabaRacesWS;

import java.sql.*;

import javax.sql.*;
import javax.naming.*;
import java.util.Date;

public class ArabaRacesService {

  private RaceDTO[] races = null;

    public ArabaRacesService() {
        System.out.println("Service Instance Creation ... " + new Date());
        setRaces();
    }

    public void setRaces() 
    {
        try {
                Context initCtx = new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");
                DataSource ds = (DataSource) envCtx.lookup("jdbc/arabaRacesDB");
                Connection con = ds.getConnection();

                Statement stat = con.createStatement();
          ResultSet rs = stat.executeQuery("Select count(*) from races;");

          races = new RaceDTO[rs.getInt(1)];

          rs = stat.executeQuery("Select * from races;");

                int i=0;
                while(rs.next()){
                      RaceDTO r = new RaceDTO(rs.getString("name"), rs.getFloat("distance"), rs.getString("date"), rs.getInt("places"));
                        races[i]= r;
                        i++;
                }

                con.close();
                stat.close();
                rs.close();

        } catch (NamingException e) {
                e.printStackTrace();
        } catch (SQLException e) {
                e.printStackTrace();
        }
    }

    public RaceDTO[] getRaces() 
    {
      return races;  
    }
}